﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.Collections;
namespace FinalProjectLogicLayer
{
    /// <summary>
    /// This Class is cool
    /// </summary>
    class xmlHandler
    {
        /// <summary>
        /// This method saves the programs information to a file
        /// </summary>
        /// <param name="saveFileName"></param>
        /// <param name="fileList"></param>
        /// <param name="dictionary"></param>
        /// <param name="matchingDiatance"></param>
        /// <param name="distance"></param>
        /// <param name="NumberOfClusters"></param>
        /// <param name="clusteringMethod"></param>
        /// <param name="clusteringResultsComments"></param>
        /// <param name="lables"></param>
        public static void saveFile(String saveFileName, FileList fileList, Dictionary dictionary, int matchingDiatance, Clustering.DistanceMeasurement distance, int NumberOfClusters, String clusteringMethod, String clusteringResultsComments,String lables)
        {
            createNewXmlSaveFile(saveFileName, "CIPHER_TEXT_ANALISYS_USING_CSV_SAVE_FILE"); //create the save file
            addValidFlagToXmlDataBase(saveFileName, fileList.ValidCSVs);
            foreach (FileInfo file in fileList)
            {
                addFileToXmlDataBase(saveFileName, file.FilePath, file.Label, file.Comments, file.DivisionParameter, file.FeatureVectors,file.DictionaryID);
            }
            addFileListAlphaBetSizeToXmlDataBase(saveFileName, fileList.LastSizeOfTheAlphaBet.ToString());
            addDictionaryToXmlSaveFile(saveFileName, dictionary.DictionaryWords, dictionary.DictionarySize, dictionary.WordSize, dictionary.SourceFileName,dictionary.DictionaryAlphaBetSize);
            addStringMatchingSettingsToXmlSaveFile(saveFileName, matchingDiatance, Enum.GetName(typeof(Clustering.DistanceMeasurement), distance));
            addClusteringSettingsToXmlSaveFile(saveFileName, clusteringMethod, NumberOfClusters);
            addClusteringResultsCommentsToXmlSaveFile(saveFileName, clusteringResultsComments);
            addLablesToXmlSaveFile(saveFileName, lables);

        }
        /// <summary>
        /// This method creates a new xml save file
        /// </summary>
        /// <param name="filepath">file path</param>
        private static void createNewXmlSaveFile(String filepath)
        {
            createNewXmlSaveFile(filepath,"SAVE_DATA_"+ filepath.Substring(filepath.LastIndexOf('\\')));
        }

        /// <summary>
        /// This method creates a NewXml Save File
        /// </summary>
        /// <param name="filepath">filePath(filename) to be saved</param>
        /// <param name="xmlRootElementId">root elemnts name</param>
        private static void createNewXmlSaveFile(String filepath, String xmlRootElementId)
        {
            //Create
            //XmlTextWriter class is used to create an Xml file. In this, 
            //we just specify the filepath and type of xml encoding.after that, we have to create a root element of xml document.
            //Ex: We are going to create an xml file with CustomerDetails as root element
            //CREATE A NEW XML
            XmlTextWriter xtw;  //create instance for xmltextwriter. Xml Text Writer
            xtw = new XmlTextWriter(filepath, Encoding.UTF8);//assign  file path and encoding
            xtw.WriteStartDocument(); //write start document
            xtw.WriteStartElement(xmlRootElementId); //create root element
            xtw.WriteEndElement(); //end root element
            xtw.Close(); //close file. It is automatically saved.
            //ADD THE ELEMENTS FOR SAVING DATA
            XmlDocument xd = new XmlDocument();     //object creation for XmlDocument class
            FileStream lfile = new FileStream(filepath, FileMode.Open); //open an xml file using file stream
            xd.Load(lfile); //load opened file in xml document
            //Add FileList Node
            XmlElement cl = xd.CreateElement("FILE_LIST"); //create an xml element                      
            xd.DocumentElement.AppendChild(cl); //append root element to xml document
            //Add DICTIONARY Node
            cl = xd.CreateElement("DICTIONARY"); //create an xml element                      
            xd.DocumentElement.AppendChild(cl); //append root element to xml document

            //Add STRING_MATCHING Node
            cl = xd.CreateElement("STRING_MATCHING"); //create an xml element
            xd.DocumentElement.AppendChild(cl); //append root element to xml document

            //Add CLUSTERING_SETTINGS Node
            cl = xd.CreateElement("CLUSTERING_SETTINGS"); //create an xml element
            xd.DocumentElement.AppendChild(cl); //append root element to xml document

            //Add STRING_MATCHING Node
            cl = xd.CreateElement("LABLES"); //create an xml element
            xd.DocumentElement.AppendChild(cl); //append root element to xml document

            lfile.Close(); //close the file stream
            xd.Save(filepath); //save the xmldocument content to the file
        }
        /// <summary>
        /// This method adds the alphaBet size used for the cretion of the filelist
        /// </summary>
        /// <param name="saveFilePath">The path of the saved file</param>
        /// <param name="AlphaBetSize">The alphaBet size as a String</param>
        private static void addFileListAlphaBetSizeToXmlDataBase(String saveFilePath,String AlphaBetSize)
        {

            XmlDocument xd = new XmlDocument();     //object creation for XmlDocument class
            FileStream lfile = new FileStream(saveFilePath, FileMode.Open); //open an xml file using file stream
            xd.Load(lfile); //load opened file in xml document
            XmlNode fileListNode = xd.GetElementsByTagName("FILE_LIST")[0]; //Files are added to the File List element in the XML document
            XmlElement fileElement = xd.CreateElement("FILE_LIST_ALPHA_BET_SIZE"); //create an xml element

            fileElement.InnerText = AlphaBetSize;
            fileListNode.AppendChild(fileElement);

            lfile.Close(); //close the file stream
            xd.Save(saveFilePath); //save the xmldocument content to the file
        }

        private static void addValidFlagToXmlDataBase(String saveFilePath, bool Valid )
        {

            XmlDocument xd = new XmlDocument();     //object creation for XmlDocument class
            FileStream lfile = new FileStream(saveFilePath, FileMode.Open); //open an xml file using file stream
            xd.Load(lfile); //load opened file in xml document
            XmlNode fileListNode = xd.GetElementsByTagName("FILE_LIST")[0]; //Files are added to the File List element in the XML document
            XmlElement fileElement = xd.CreateElement("VALID"); //create an xml element
            fileElement.InnerText = "" + Valid;

            fileListNode.AppendChild(fileElement);

            lfile.Close(); //close the file stream
            xd.Save(saveFilePath); //save the xmldocument content to the file
        }

        /// <summary>
        /// This method adds file to the file list section of the XML save file
        /// </summary>
        /// <param name="saveFilePath">Path of the save file to add this file too</param>
        /// <param name="filePath">The file path of the input file</param>
        /// <param name="fileLabel">The label of the input file</param>
        /// <param name="fileComment">The comment of the input file</param>
        /// <param name="divParametr">The div parameter of the input file</param>
        /// <param name="CSV">The csv vector of the input file</param>
        private static void addFileToXmlDataBase(String saveFilePath, String filePath,String fileLabel,String fileComment,int divParametr,ArrayList csvList,String dictionaryID)
        {
            //Write- [insert into database]
            //We can add data into an xml file by just adding child nodes to the root element. In this, we just create some
            // xml elements and append those elements to the root as a child element and save the xml document.
            //Before writing, one thing is very important. All the data stored into the xml 
            //file will be treated as String only. So we must convert all data types to string.

            XmlDocument xd = new XmlDocument();     //object creation for XmlDocument class
            FileStream lfile = new FileStream(saveFilePath, FileMode.Open); //open an xml file using file stream
            xd.Load(lfile); //load opened file in xml document
            XmlNode fileListNode = xd.GetElementsByTagName("FILE_LIST")[0]; //Files are added to the File List element in the XML document
            XmlElement fileElement = xd.CreateElement("FILE"); //create an xml element
            appendChildToNode(xd, fileElement, "PATH", filePath);
            appendChildToNode(xd, fileElement, "LABEL", fileLabel);
            appendChildToNode(xd, fileElement, "COMMENT", fileComment); 
            appendChildToNode(xd, fileElement, "DIV_PARAMETER", "" + divParametr);
            appendChildToNode(xd, fileElement, "DICTIONARY_ID", "" + dictionaryID);

            foreach (double[] CSV in csvList) //go over all the vectors belonging to this file
            {
                String csvString = ""; //convert each csv to String
                if (CSV != null)
                {
                    foreach (double num in CSV)
                        csvString += num + ",";
                    csvString = csvString.Substring(0, csvString.LastIndexOf(",")); //delete last ","
                }
                appendChildToNode(xd, fileElement, "CSV", csvString); //and appand the string to the FILE_LIST element
            }

           
            fileListNode.AppendChild(fileElement);
            
            lfile.Close(); //close the file stream
            xd.Save(saveFilePath); //save the xmldocument content to the file
        }
        
        /// <summary>
        /// This method adds a cluster to the Save file
        /// </summary>
        /// <param name="filePath">filePath of the file to saved</param>
        /// <param name="cluster">cluster data</param>
        private static void addClusteringResultsToXmlSaveFile(String filePath,int[] cluster)
        {
            XmlDocument xd = new XmlDocument();     //object creation for XmlDocument class
            FileStream lfile = new FileStream(filePath, FileMode.Open); //open an xml file using file stream
            xd.Load(lfile); //load opened file in xml document
            if (xd.GetElementsByTagName("CLUSTERING_RESULTS").Count == 0) //No clustering results added yet
            {
                XmlNode fileListNode = xd.GetElementsByTagName("FILE_LIST")[0]; //Clustering Results  are added to the File List element in the XML document
                XmlElement clusteringElement = xd.CreateElement("CLUSTERING_RESULTS"); //create an xml element
                fileListNode.AppendChild(clusteringElement);
            }
            
            String clusterString = ""; //convert the csv to String
            if (cluster != null)
            {
                foreach (int num in cluster)
                    clusterString += num + ",";
                clusterString = clusterString.Substring(0, clusterString.LastIndexOf(",")); //delete last ","
            }

            XmlNode clusteringResultsNode = xd.GetElementsByTagName("CLUSTERING_RESULTS")[0]; //Files are added to the File List element in the XML document          
            appendChildToNode(xd, clusteringResultsNode, "CLUSTER", clusterString);

            lfile.Close(); //close the file stream
            xd.Save(filePath); //save the xmldocument content to the file
        }

        /// <summary>
        /// Method adds clustering results comments to the save file
        /// </summary>
        /// <param name="filePath">the file path of the file to save</param>
        /// <param name="comment">the clustering result comment</param>
        private static void addClusteringResultsCommentsToXmlSaveFile(String filePath,String comment)
        {
            XmlDocument xd = new XmlDocument();     //object creation for XmlDocument class
            FileStream lfile = new FileStream(filePath, FileMode.Open); //open an xml file using file stream
            xd.Load(lfile); //load opened file in xml document
            if (xd.GetElementsByTagName("CLUSTERING_RESULTS").Count == 0) //No clustering results added yet
            {
                XmlNode fileListNode = xd.GetElementsByTagName("FILE_LIST")[0]; //Clustering Results  are added to the File List element in the XML document
                XmlElement clusteringElement = xd.CreateElement("CLUSTERING_RESULTS"); //create an xml element
                fileListNode.AppendChild(clusteringElement);
            }
            XmlNode clusteringResultsNode = xd.GetElementsByTagName("CLUSTERING_RESULTS")[0]; //GetTheClusteringResultsElement
            XmlNodeList clusterList = clusteringResultsNode.ChildNodes;
            bool foundComments = false;
            foreach (XmlElement element in clusterList) //Find the Comments Child and modify it
            {
                if (element.Name == "COMMENTS")
                {
                    foundComments = true;
                    element.InnerText = comment;
                    break;
                }
            }
            if (!foundComments) // If no comments child exsists Create a new one
                appendChildToNode(xd, clusteringResultsNode, "COMMENTS", comment);

            lfile.Close(); //close the file stream
            xd.Save(filePath); //save the xmldocument content to the file
        }

        /// <summary>
        /// This method saves dictionary to the XML save file
        /// </summary>
        /// <param name="filePath">path of the XML save file</param>
        /// <param name="dictionaryWords">Array of the dictionary strings</param>
        /// <param name="dictionaryLength">dictionary length(number of words in the dictionary)</param>
        /// <param name="wordLength">dictionary word length</param>
        /// <param name="dictionarySource">dictionary source file</param>
        private static void addDictionaryToXmlSaveFile(String filePath,String[] dictionaryWords,int dictionaryLength,int wordLength,String dictionarySource,int dictionaryAlphaBetSize)
        {
            XmlDocument xd = new XmlDocument();     //object creation for XmlDocument class
            FileStream lfile = new FileStream(filePath, FileMode.Open); //open an xml file using file stream
            xd.Load(lfile); //load opened file in xml document
            XmlNode dictionaryNode = xd.GetElementsByTagName("DICTIONARY")[0]; //Files are added to the File List element in the XML document
            dictionaryNode.InnerXml = ""; //delete previos dictionary entries
            
            String dictionaryWordsString = ""; //convert dictionary words array to String
            if (dictionaryWords != null)
            {
                foreach (String word in dictionaryWords)
                    dictionaryWordsString += word;// + ",";
                //dictionaryWordsString = dictionaryWordsString.Substring(0, dictionaryWordsString.LastIndexOf(",")); //delete last ","
            }
            appendChildToNode(xd, dictionaryNode, "WORDS", dictionaryWordsString);
            appendChildToNode(xd, dictionaryNode, "LENGTH", "" + dictionaryLength);
            appendChildToNode(xd, dictionaryNode, "WORDS_LENGTH", "" + wordLength);
            appendChildToNode(xd, dictionaryNode, "SOURCE_FILE", "" + dictionarySource);
            appendChildToNode(xd, dictionaryNode, "DICTIONARY_ALPHABET_SIZE", "" + dictionaryAlphaBetSize);
            lfile.Close(); //close the file stream
            xd.Save(filePath); //save the xmldocument content to the file
        }


        private static void addStringMatchingSettingsToXmlSaveFile(String filePath,int matchingDistance,String matchingAlgoithm)
        {
            XmlDocument xd = new XmlDocument();     //object creation for XmlDocument class
            FileStream lfile = new FileStream(filePath, FileMode.Open); //open an xml file using file stream
            xd.Load(lfile); //load opened file in xml document
            XmlNode dictionaryNode = xd.GetElementsByTagName("STRING_MATCHING")[0]; //Files are added to the File List element in the XML document
            dictionaryNode.InnerXml = ""; //delete previos setting entries
            appendChildToNode(xd, dictionaryNode, "MATCHING_DISTANCE", "" + matchingDistance);
            appendChildToNode(xd, dictionaryNode, "ALGORITHEM", matchingAlgoithm);

            lfile.Close(); //close the file stream
            xd.Save(filePath); //save the xmldocument content to the file
        }

        /// <summary>
        /// This method adds the clustering settings to a XML save file
        /// </summary>
        /// <param name="filePath">the path of the save file</param>
        /// <param name="distanceMethod">String representing the distance method</param>
        /// <param name="numberOfClusters">the number of clusters in the process</param>
        private static void addClusteringSettingsToXmlSaveFile(String filePath,String distanceMethod,int numberOfClusters)
        {
            XmlDocument xd = new XmlDocument();     //object creation for XmlDocument class
            FileStream lfile = new FileStream(filePath, FileMode.Open); //open an xml file using file stream
            xd.Load(lfile); //load opened file in xml document
            XmlNode clusteringSettingsNode = xd.GetElementsByTagName("CLUSTERING_SETTINGS")[0]; //Files are added to the File List element in the XML document
            clusteringSettingsNode.InnerXml = ""; //delete previos setting entries
            appendChildToNode(xd, clusteringSettingsNode, "CLUSTERING_METHOD", distanceMethod);
            if (numberOfClusters < 1) numberOfClusters = 1;
            appendChildToNode(xd, clusteringSettingsNode, "NUMBER_OF_CLUSTERS", "" +numberOfClusters);

            lfile.Close(); //close the file stream
            xd.Save(filePath); //save the xmldocument content to the file
        }
        
        /// <summary>
        /// This method Addes lables to the XML save file
        /// </summary>
        /// <param name="filePath">file path of the save file</param>
        /// <param name="lables">String containing all the lables seperated by commas</param>
        private static void addLablesToXmlSaveFile(String filePath,String lables)
        {
            XmlDocument xd = new XmlDocument();     //object creation for XmlDocument class
            FileStream lfile = new FileStream(filePath, FileMode.Open); //open an xml file using file stream
            xd.Load(lfile); //load opened file in xml document
            XmlNode dictionaryNode = xd.GetElementsByTagName("LABLES")[0]; //Files are added to the File List element in the XML document
            dictionaryNode.InnerText = lables; //delete previos setting entries

            lfile.Close(); //close the file stream
            xd.Save(filePath); //save the xmldocument content to the file
        }
        /// <summary>
        /// This method appends a child node to an element
        /// </summary>
        /// <param name="xd">The xml document</param>
        /// <param name="Node">The node of the element we want to attach a child elemnt to</param>
        /// <param name="newChild">the child element to append</param>
        /// <param name="childsText">the childs element text</param>
        private static void appendChildToNode(XmlDocument xd, XmlNode Node, String newChild, String childsText)
        {
            XmlElement childElement = xd.CreateElement(newChild); //create an xml element
            XmlText childElementsText = xd.CreateTextNode(childsText); //create text for xml element
            childElement.AppendChild(childElementsText); //append address text to address node
            Node.AppendChild(childElement); //append address node to root element
        }

        /*******************************************************************************************************************************/   
        /// <summary>
        /// Convert comma seperated doubles string to an array of doubles
        /// </summary>
        /// <param name="doubleString">comma seperated doubles</param>
        /// <returns>an array of the double numbers</returns>
        private static double[] stringToDoubleArray(String doubleString)
        {
            String[] splited = doubleString.Split(',');
            double[] doubleArray = new double[splited.Length];
            for (int i=0; i<doubleArray.Length; i++)
            {
                doubleArray[i] = double.Parse(splited[i]);
            }
            return doubleArray;
        }

        /// <summary>
        /// This method loads a FileList from a given file
        /// </summary>
        /// <param name="filePath">Path of the file to load</param>
        /// <returns>file list and file information from the loaded file</returns>
        public static FileList LoadFilelist(String filePath)
        {
            XmlDocument xdoc = new XmlDocument(); //creation of XmlDocument class Instance
            FileStream rfile = new FileStream(filePath, FileMode.Open); //create a file stream and open the file to be updated
            xdoc.Load(rfile);//load file into xmldocument instance
            

            XmlNodeList fileList = xdoc.GetElementsByTagName("FILE"); //find out the no of elements available in xml file   
            FileList loadedFileList = new FileList();
            foreach (XmlElement file in fileList) //For all the files
            {
                FileInfo loadedFile = new FileInfo();  //create a new file info
                foreach (XmlNode info in file.ChildNodes) //load all information of the file from XML
                {
                    switch (info.LocalName)
                    {
                        case "PATH":
                            loadedFile.FilePath = info.InnerText;
                            break;
                        case "COMMENT":
                            loadedFile.Comments = info.InnerText;        
                            break;
                        case "DICTIONARY_ID":
                            loadedFile.DictionaryID = info.InnerText;
                            break;
                        case "LABEL":
                            loadedFile.Label = info.InnerText;
                            break;
                        case "DIV_PARAMETER":
                            loadedFile.DivisionParameter = int.Parse(info.InnerText);
                                    break;
                        case "CSV":
                                    loadedFile.FeatureVectors.Add(stringToDoubleArray(info.InnerText));
                                    break;
                    }
                }
                loadedFileList.Add(loadedFile);     
            }
            //Load alphaBetSize in use
            XmlNode  fileListAlphaBetSize = xdoc.GetElementsByTagName("FILE_LIST_ALPHA_BET_SIZE")[0];
            loadedFileList.LastSizeOfTheAlphaBet = int.Parse(fileListAlphaBetSize.InnerText);
            //LOAD IF CSV's Are valid
            XmlNode fileListIsValid = xdoc.GetElementsByTagName("VALID")[0];
            loadedFileList.ValidCSVs = bool.Parse(fileListIsValid.InnerText);

            rfile.Close(); //close the file stream
            return loadedFileList;
        }

        /// <summary>
        /// This method splits a string to specific part size
        /// </summary>
        /// <param name="s">input string</param>
        /// <param name="partSize">the size of the each splitted substring</param>
        /// <returns>Retuns a string array that contains the splitted parts</returns>
        private static String[] splitString(String s, int partSize)
        {
            String[] stringArray = null;
            if (partSize == 0)
            {
                stringArray = new String[1];
                stringArray[0] = s;
                return stringArray;
            }

            while (s.Length % partSize != 0)
            {
                s += " ";
            }
            
            stringArray = new String[s.Length / partSize];
            for (int i = 0; i < stringArray.Length; i++)
            {
                stringArray[i] = s.Substring(0, partSize);
                s = s.Substring(partSize);
            }
            return stringArray;
        }

        /// <summary>
        /// This method loads a dictionary from a file
        /// </summary>
        /// <param name="filePath">the path of the file to load from</param>
        /// <returns>Returns a dictionary variable</returns>
        public static Dictionary LoadDictionary(String filePath)
        {
            XmlDocument xdoc = new XmlDocument(); //creation of XmlDocument class Instance
            FileStream rfile = new FileStream(filePath, FileMode.Open); //create a file stream and open the file to be updated
            xdoc.Load(rfile);//load file into xmldocument instance
            XmlNodeList dictionaryElements = xdoc.GetElementsByTagName("DICTIONARY"); //find out the no of elements available in xml file   
            Dictionary loadedDictionary = new Dictionary();
            foreach (XmlElement dictionary in dictionaryElements) //For all the dictionarys (althogh there is only one)
            {
                String tempDictionaryWords = "";

                foreach (XmlNode info in dictionary.ChildNodes) //load all information of the file from XML
                {
                    switch (info.LocalName)
                    {
                        case "WORDS":
                            tempDictionaryWords = info.InnerText;
                            break;
                        case "LENGTH":
                            loadedDictionary.DictionarySize = int.Parse(info.InnerText);
                            break;
                        case "WORDS_LENGTH":
                            loadedDictionary.WordSize = int.Parse(info.InnerText);
                            break;
                        case "SOURCE_FILE":
                            loadedDictionary.SourceFileName = info.InnerText;
                            break;
                        case "DICTIONARY_ALPHABET_SIZE":
                            loadedDictionary.DictionaryAlphaBetSize = int.Parse(info.InnerText);
                            break;
                    }
                }
                loadedDictionary.DictionaryWords = splitString(tempDictionaryWords, loadedDictionary.WordSize);
            }
            rfile.Close(); //close the file stream
            return loadedDictionary;
        }

        /// <summary>
        /// The method loads the string matching settings
        /// </summary>
        /// <param name="filePath">filepath of the file to load string matchings settings from </param>
        /// <returns>Retuns and array of strings array[0] = maching distance, array[1] = matching algorithem</returns>
        public static String[] loadStringMatchingSettings(String filePath)
        {
            XmlDocument xdoc = new XmlDocument(); //creation of XmlDocument class Instance
            FileStream rfile = new FileStream(filePath, FileMode.Open); //create a file stream and open the file to be updated
            xdoc.Load(rfile);//load file into xmldocument instance
            XmlNodeList stringMatchinglist = xdoc.GetElementsByTagName("STRING_MATCHING"); //find out the no of elements available in xml file   
            String[] loadedSettings = new String[2]; //create a new String array
            foreach (XmlElement stringMatchingElement in stringMatchinglist) //For all the dictionarys (althogh there is only one)
            {
                foreach (XmlNode info in stringMatchingElement.ChildNodes) //load all information of the file from XML
                {
                    switch (info.LocalName)
                    {
                        case "MATCHING_DISTANCE":
                            loadedSettings[0] = info.InnerText;
                            break;
                        case "ALGORITHEM":
                            loadedSettings[1] = info.InnerText;
                            break;
                    }
                }
            }
            rfile.Close(); //close the file stream
            return loadedSettings;
        }

        /// <summary>
        /// The method loads the clustering settings
        /// </summary>
        /// <param name="filePath">filepath of the file to load string matchings settings from </param>
        /// <returns>Retuns and array of strings array[0] = clustering method, array[1] = number of clusters</returns>
        public static String[] loadClusteringSettings(String filePath)
        {
            XmlDocument xdoc = new XmlDocument(); //creation of XmlDocument class Instance
            FileStream rfile = new FileStream(filePath, FileMode.Open); //create a file stream and open the file to be updated
            xdoc.Load(rfile);//load file into xmldocument instance
            XmlNodeList clusteringMatchinglist = xdoc.GetElementsByTagName("CLUSTERING_SETTINGS"); //find out the no of elements available in xml file   
            String[] loadedSettings = new String[2]; //create a new String array
            foreach (XmlElement clusteringElement in clusteringMatchinglist) //For all the dictionarys (althogh there is only one)
            {
                foreach (XmlNode info in clusteringElement.ChildNodes) //load all information of the file from XML
                {
                    switch (info.LocalName)
                    {
                        case "CLUSTERING_METHOD":
                            loadedSettings[0] = info.InnerText;
                            break;
                        case "NUMBER_OF_CLUSTERS":
                            loadedSettings[1] = info.InnerText;
                            break;
                    }
                }
            }
            rfile.Close(); //close the file stream
            return loadedSettings;
        }

        /// <summary>
        /// The method loads the clustering results comments
        /// </summary>
        /// <param name="filePath">filepath of the file to load string matchings settings from </param>
        /// <returns>Retuns string of the comments</returns>
        public static String loadClusteringResultsComments(String filePath)
        {
            XmlDocument xdoc = new XmlDocument(); //creation of XmlDocument class Instance
            FileStream rfile = new FileStream(filePath, FileMode.Open); //create a file stream and open the file to be updated
            xdoc.Load(rfile);//load file into xmldocument instance
            XmlNodeList clusteringREsultsCommentslist = xdoc.GetElementsByTagName("CLUSTERING_RESULTS"); //find out the no of elements available in xml file   
            String loadedComments = ""; //create a new String array
            foreach (XmlElement clusteringCommentsElement in clusteringREsultsCommentslist) //For all the dictionarys (althogh there is only one)
            {
                foreach (XmlNode info in clusteringCommentsElement.ChildNodes) //load all information of the file from XML
                {
                    switch (info.LocalName)
                    {
                        case "COMMENTS":
                            loadedComments = info.InnerText;
                            break;
                    }
                }
            }
            rfile.Close(); //close the file stream
            return loadedComments;
        }

        public static void saveLables(String lables,String filePath)
        {
            createNewXmlSaveFile(filePath, "CIPHER_TEXT_ANALISYS_USING_CSV_LABLES_FILE"); //create the save file

            addLablesToXmlSaveFile(filePath, lables);

        }
        /// <summary>
        /// This method returns saved lables
        /// </summary>
        /// <param name="filePath">file path to load lables from</param>
        /// <returns>Returns an array of strings contiaing the lables loaded from the file</returns>
        public static String[] loadSavedLables(String filePath)
        {
            XmlDocument xdoc = new XmlDocument(); //creation of XmlDocument class Instance
            FileStream rfile = new FileStream(filePath, FileMode.Open); //create a file stream and open the file to be updated
            xdoc.Load(rfile);//load file into xmldocument instance
            XmlNodeList clusteringMatchinglist = xdoc.GetElementsByTagName("LABLES"); //find out the no of elements available in xml file   
            String[] loadedLables = clusteringMatchinglist[0].InnerText.Split(',');
            rfile.Close(); //close the file stream
            return loadedLables;
        }
    }
}
